import React, { useState } from 'react';
import { Input, Card, List, Space, Empty, message, Typography } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import styles from './index.module.css';
import { searchContent } from '@/services/auth';

const { Search } = Input;
const { Title, Paragraph } = Typography;

interface SearchResult {
  id: string;
  content: string;
  createdAt: string;
  user: {
    name: string;
    avatar: string;
  };
}

const SearchPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState<SearchResult[]>([]);
  const [current, setCurrent] = useState(1);
  const [total, setTotal] = useState(0);
  const [keyword, setKeyword] = useState('');
  const pageSize = 10;

  const handleSearch = async (searchKeyword: string, currentPage: number = 1) => {
    if (!searchKeyword.trim()) {
      message.warning('请输入搜索关键词');
      return;
    }

    setKeyword(searchKeyword);
    setLoading(true);
    try {
      const data = await searchContent(searchKeyword, currentPage, pageSize);
      setResults(data.items || []);
      setTotal(data.total);
      setCurrent(currentPage);
    } catch (error) {
      console.error('搜索失败:', error);
      message.error(error instanceof Error ? error.message : '搜索失败');
    } finally {
      setLoading(false);
    }
  };

  const handlePageChange = (newPage: number) => {
    if (keyword) {
      handleSearch(keyword, newPage);
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <Title level={2} className={styles.title}>电力知识库检索系统</Title>
        <Search
          placeholder="请输入关键词搜索电力知识..."
          enterButton={<>搜索 <SearchOutlined /></>}
          size="large"
          loading={loading}
          onSearch={(value) => handleSearch(value, 1)}
          className={styles.searchInput}
        />
      </div>

      <div className={styles.resultWrapper}>
        {results.length > 0 ? (
          <List
            className={styles.resultList}
            itemLayout="vertical"
            dataSource={results}
            pagination={{
              current,
              pageSize,
              total,
              onChange: handlePageChange,
              showTotal: (total) => `共 ${total} 条结果`
            }}
            renderItem={(item) => (
              <List.Item
                key={item.id}
                className={styles.listItem}
              >
                <div className={styles.content}>
                  <div className={styles.text}>{item.content}</div>
                  <div className={styles.meta}>来源：系统知识库</div>
                </div>
              </List.Item>
            )}
          />
        ) : (
          <Empty description="请输入关键词开始搜索" />
        )}
      </div>
    </div>
  );
};

export default SearchPage;